﻿namespace LogManager.Utils.Unity
{
    using Microsoft.Practices.Unity;
    using Microsoft.Practices.Unity.InterceptionExtension;

    public static class UnityHelpers
    {
        public static void RegisterForInterception<TClass>(this IUnityContainer container, LifetimeManager lifetimeManager, InterceptionBehavior interceptionBehavior) where TClass : class
        {
            container.RegisterType<TClass, TClass>(lifetimeManager, interceptionBehavior);
        }

        public static void RegisterForInterception<TClass>(this IUnityContainer container, InterceptionBehavior interceptionBehavior) where TClass : class
        {
            container.RegisterType<TClass, TClass>(interceptionBehavior);
        }

        public static T Resolve<Tparam, T>(this IUnityContainer container, Tparam parameter)
        {
            return container.Resolve<T>(new DependencyOverride<Tparam>(parameter));
        }

        public static T Resolve<Tparam1, Tparam2, T>(this IUnityContainer container, Tparam1 parameter1, Tparam2 parameter2)
        {
            return container.Resolve<T>(new DependencyOverride<Tparam1>(parameter1), new DependencyOverride<Tparam2>(parameter2));
        }

        public static T Resolve<Tparam1, Tparam2, Tparam3, T>(this IUnityContainer container, Tparam1 parameter1, Tparam2 parameter2, Tparam3 parameter3)
        {
            return container.Resolve<T>(new DependencyOverride<Tparam1>(parameter1), new DependencyOverride<Tparam2>(parameter2), new DependencyOverride<Tparam3>(parameter3));
        }

        public static TAbstraction TryResolve<TAbstraction, TImplementation>(this IUnityContainer container)
            where TImplementation : TAbstraction
        {
            if (container.IsRegistered<TAbstraction>())
            {
                return container.Resolve<TAbstraction>();
            }
            else
            {
                return container.Resolve<TImplementation>();
            }
        }
    }
}
